<script setup>
// import HelloWorld from './components/HelloWorld.vue'
// import TheWelcome from './components/TheWelcome.vue'
</script>

<template>
  <el-container>
    <el-header>Header</el-header>
    <el-container>
      <el-aside width="100px">Aside
        <div>
          <p>控制按钮</p>
          <button @click="start">开始聊天</button>
          <button @click="send_input">发送内容</button>
          <button @click="get_result">获得响应</button>
          <button @click="close">关闭聊天</button>
          <button @click="force_close">强制关闭聊天</button>
          <br />
        </div>
      </el-aside>
      <el-container>
        <el-main>
          <div id="up_divider">
            <el-divider style="margin: 0 0 10px 0;" />
          </div>
          <div id="result">
            <!-- <div class="code-container" ref="container">
              <slot></slot>
            </div> -->
            <div v-for="post in chats" :key="post.value">
              <div>
                <el-icon>
                  <User />
                </el-icon>
                <p class="user">{{ post.user }}</p>
              </div>
              <div>
                <el-icon>
                  <Comment />
                </el-icon>
                <p class="robot">{{ post.robot }}</p>
                <!--<div v-for="robot_data in post.robot" :key="post.robot.value">
                   <div v-if="post.robot.is_code" ref="{{post.robot.code_id}}"></div> 
                  <div v-if="post.robot.is_common_content">
                    <p class="robot">{{ post.robot.data }}</p>
                  </div>
                </div>-->
              </div>
            </div>
          </div>
          <div id="question">
            <el-input v-model="input" :rows="4" type="textarea" placeholder="请输入发送内容" />
          </div>
          <div id="down_divider">
            <el-divider />
          </div>
        </el-main>
        <el-footer>Footer</el-footer>
      </el-container>
    </el-container>
  </el-container>
</template>

<script>
import axios from "axios";
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import * as monaco from "monaco-editor";

const input = ref('')
var input_string_list = []
var output_string_list = []

const config = {
  headers: {
    'Content-Type': 'application/json; charset=utf-8', // 设置字符编码为 UTF-8  
  },
};

export default {
  props: {
    code: {
      type: String,
      default: "#include <stdio.h>",
    },
  },
  data() {
    return {
      /**
       * key: user/robot, 
       *   key是user时,value是一个字符串；
       *   key是robot时，value是一个列表：每个是一个对象 {'is_code': 是否代码, 'is_common_content': 是否普通字符串, 'data': 字符串数据}，其中is_code/is_common_content有且仅有一个true
       */
      chats: [], 
      
      monacoEditor: {},
      monaco_codes: [],  // {'content': 代码片段字符串}
    };
  },
  methods: {
    init() {
      this.monacoEditor = monaco.editor.create(this.$refs.container, {
        value: this.code, //                                                        代码
        readOnly: true, //                                                          只读
        language: "c", //                                                           语法
        theme: "vs-dark", //                                                        主题            vs/vs-dark/hc-black （可使用defineTheme中的主题）
        folding: true, //                                                           代码折叠
        position: true,
        // showFoldingControls: "always",//                                         折叠图标显示     mouseover/always
        quickSuggestions: true, //                                                  支持搜索         ctrl + F
        automaticLayout: true, //                                                   resize自动布局
        cursorStyle: "line", //                                                     光标样式         line/block/underline/line-thin/block-outline/underline-thin
        roundedSelection: true, //                                                  控制选区是否有圆角
      });
    },
    test() {

    },
    // 每3个``` + 3个```包住的，作为一个新的代码块，进行拆分
    // 每个<EOF>作为换行符
    split_chat_content(raw_content) {
      this.monaco_codes = []
      const arr = raw_content.replace(/\n/g, '<br>').split('```');
      // 1a```code1```你好```code2```再见
      // 下表1、3、5...奇数的是代码
      var return_content = []
      for (var index = 0; index < arr.length; ++index) {
        if (index % 2 == 0) {
          return_content.push({'is_code': false, 'is_common_content': true, 'data': arr[index]});
        } else {
          return_content.push({'is_code': true, 'is_common_content': false, 'data': arr[index]});
          this.monaco_codes.push({'content': arr[index]})
        }
      }
      return return_content;
    },
    dealWithError(error, inp_message) {
      console.log(error);
      ElMessage({
        showClose: true,
        message: inp_message,
        type: 'error',
      })
    },
    refreshResult() {
      // let display = "";
      console.log(input_string_list);
      console.log(output_string_list);
      this.chats = [];
      for (let i = 0; i < input_string_list.length; i++) {
        // display += "用户：" + input_string_list[i] + "<br>";
        // display += "结果：" + output_string_list[i] + "<br>";
        this.chats.push({ 'user': input_string_list[i], 'robot': output_string_list[i] });
        var temp = this.split_chat_content(output_string_list[i]);
        console.log(temp);
      }
      console.log(this.chats);
    },
    start() {
      // this.init();
      axios.post('/chat/start',
        '',
        config
      )
        .then(response => {
          ;
        })
        .catch(error => {
          this.dealWithError(error, "打开失败。");
        });
    },
    send_input() {
      console.log(input.value);
      axios.post('/chat/input',
        //JSON.stringify(input.value),
        input.value,
        config
      )
        .then(response => {
          this.display = response;
          input_string_list.push(input.value);
        }
        )
        .catch(error => {
          this.dealWithError(error, "输入失败。");
        });
    },
    get_result() {
      axios.get('/chat/get_result',
        '',
        config
      )
        .then(response => {
          output_string_list.push(response.data);
          //output_string_list.push(JSON.parse(response));
          this.refreshResult();
        }
        )
        .catch(error => {
          this.dealWithError(error, "获取结果失败。");
        });
    },
    close() {
      axios.post('/chat/close',
        '',
        config
      )
        .then(response => {
          ;
        }
        )
        .catch(error => {
          this.dealWithError(error, "关闭失败。");
        });
    },
    force_close() {
      axios.post('/chat/force_close',
        '',
        config
      )
        .then(response => {
          ;
        }
        )
        .catch(error => {
          this.dealWithError(error, "强制关闭失败。");
        });
    },
  }
}
</script>

<style scoped>
.el-container {
  padding: 0px;
  margin: 0px;
  height: 100%;
  width: 100%;
}

.el-footer {
  height: 60px;
  background-color: #FFFFFF;
  color: #433;
}

.el-main {
  height: calc(100vh - 180px);
  background: linear-gradient(180deg, #FFFFFF, #e6ebf7);
  color: #543;
  padding: 0px 20px 0px 20px;
}

.el-header {
  height: 60px;
  background-color: #FFFFFF;
  color: #503;
}

.el-aside {
  background-color: #ECEAEE;
  color: #333;
  text-align: center;
}

#up_divider {
  height: 3%;
}

#result {
  height: 75%;
}

#question {
  height: 10%;
}

#down_divider {
  height: 3%;
}

/* .logo {
  display: block;
  margin: 0 auto 2rem;
} */


/* @media (min-width: 1024px) {
  header {
    display: flex;
    place-items: center;
    padding-right: calc(var(--section-gap) / 2);
  }

  .logo {
    margin: 0 2rem 0 0;
  }

  header .wrapper {
    display: flex;
    place-items: flex-start;
    flex-wrap: wrap;
  }
} */
</style>
